function isValidKey(string){
    var loginRegxp = /^([A-Za-z0-9_]){2,128}$/;
    return loginRegxp.test(string);
}



function addTag(pageid){
        
    if(document.getElementById('myTags').value != 'new'){
        var temp = document.getElementById('myTags').selectedIndex;
        var name = document.getElementById('myTags').options[temp].text;
    }else{
        var name  = document.getElementById("newtagname").value;      
    }

    if(name.length > 0){
        showLoad();
        (new AjaxRequest).send({
            url			: urlBase+"action=addTag",
            data		: {
                page    : pageid,
                tname   : name,
                tagid   : document.getElementById('myTags').value
            },
            
            onSuccess	: function(data, info)
            {
                if(data.added){
                    deleteRow('notags');
                    
                    //add new row to table
                    var myRows  = document.getElementById('available_tags').rows.length;
                    var myRow   = document.getElementById('available_tags').insertRow(myRows);
                    var myCell  = myRow.insertCell(0);
                    
                    myRow.id         = 'tagrow_'+data.tagid;
                    myCell.innerHTML = name+' [<a href="javascript: deleteTag('+pageid+','+data.tagid+');" class="admin">x</a>]';
                }
                
                document.getElementById("newtagname").value  = '';
                Fat.fade_element('tagrow_'+data.tagid,10,1000,"#ffffcc");
                
                //restore the view
                unhide('newTag');
                unhide('addtagbtn',true); 
                hide('addtagform',true);            
                
                if(temp){
                    document.getElementById('myTags').options[temp] = null;
                    temp = null;
                }
                
                //hide the loader
                hideLoad();
            }
        });
    }else{
        alert('Plase input a Tag Name');
    }
}


function checkNewTag(obj){
    if(obj.value == 'new'){
        unhide('newTag');
    }else{
        hide('newTag');
    }
}


function deleteTag(page,tag){
    if(confirm('Are You Sure You Want to Delete this Tag?')){
        showLoad();
        deleteme('tagrow_'+tag);
        
        (new AjaxRequest).send({
        		url			: urlBase+"action=deleteTag",
        		data		: {
        			id    : tag,
        			pid   : page
        		},
        		
        		onSuccess	: function(data, info)
        		{
        			deleteRow('tagrow_'+tag);
        			        			
                    //check if that was the only file
                    var myRows = document.getElementById('available_tags').rows.length;
                    if(myRows < 1){
                        var myTable       =   document.getElementById('available_tags').insertRow(myRows);
                        var myCellN       =   myTable.insertCell(0);
                        myCellN.innerHTML = '<div align="center"><i>No Tags</i></div>';
                        myTable.id        = 'notags';
                    }                  
                    
                    if(data.tagName){
                        var item = document.createElement("option");
                        item.setAttribute("value", tag);
                        item.appendChild(document.createTextNode(data.tagName));
                        document.getElementById('myTags').appendChild(item);
                    }
        			
                    //hide the loader
    				hideLoad();
        		}
        });
    }
}


function addProperty(nodeid, pageid){
    var name  = document.getElementById("newpropname").value;
    var value = document.getElementById("newpropvalue").value;
    
    if(isValidKey(name)){
        if(value.length > 0){
            showLoad();
            (new AjaxRequest).send({
        		url			: urlBase+"action=addProperty",
        		data		: {
        			node    : nodeid,
        			page    : pageid,
        			pname   : name,
        			pvalue  : value
        		},
        		
        		onSuccess	: function(data, info)
        		{
        			if(data["status"]){
        			    //make sure there is no "no props" row
        			    deleteRow('noprops');
        			    
        			    if(!document.getElementById('proprow_'+name)){
                			//add new row to table
                    	    var myRows  =   document.getElementById('available_properties').rows.length;
                            var myTable =   document.getElementById('available_properties').insertRow(myRows);
                            var myCellN =   myTable.insertCell(0);
                            var myCellV =   myTable.insertCell(1);
                            
                            myCellN.id        = 'proptag_'+name;
                            myCellV.id        = 'propvalue_'+name;
                            myTable.id        = 'proprow_'+name;
                            
                            myCellN.innerHTML = name+':';
                            myCellN.className = 'name';
        			    }else{
        			        var myCellN =   document.getElementById('proptag_'+name);
        			        var myCellV =   document.getElementById('propvalue_'+name);
        			    }
                        
                        myCellV.innerHTML = value+' [<a href="javascript: deleteProperty(\''+data["id"]+'\',\''+nodeid+'\',\''+pageid+'\',\''+name+'\');" class="admin">x</a>]';
                        myCellV.className = 'value';
                        
                        
                        //empty fields
                        document.getElementById("newpropname").value  = '';
                        document.getElementById("newpropvalue").value = '';
                        
                        Fat.fade_element('proprow_'+name,10,1000,"#ffffcc");
                        
                        //restore the view
                        unhide('addpropbtn',true); 
                        hide('addpropform',true);
        			}else{
        			    alert('A property with that name already exists as this level!');
        			    document.getElementById('newpropname').focus();
        			}
        			
                    //hide the loader
    				hideLoad();
        		}
        	});
        }else{
            alert("Please input some kind of value for the new property!");
        }
        
    }else{
        alert("The property name must be a single word\nand not using any special characters!");
    }
}


function deleteProperty(id,node,page,tag){
    if(confirm('Are You Sure You Want to Delete this Property?')){
        showLoad();
        deleteme('proprow_'+tag);
        
        (new AjaxRequest).send({
        		url			: urlBase+"action=deleteProperty",
        		data		: {
        			id    : id,
        			node  : node,
        			page  : page,
        			tag   : tag
        		},
        		
        		onSuccess	: function(data, info)
        		{
        			deleteRow('proprow_'+tag);
        			
        			//see if this datablock was an override of
        		    //an inheritance
        		    if(!data["inherit"]){
        		        
        			    //check if that was the only file
            		    var myRows = document.getElementById('available_properties').rows.length;
            			if(myRows < 1){
            			    var myTable       =   document.getElementById('available_properties').insertRow(myRows);
                            var myCellN       =   myTable.insertCell(0);
                            myCellN.innerHTML = '<div align="center"><i>No Properties</i></div>';
                            myTable.id        = 'noprops';
            			}
            			
        		    }else{
        		        
        		        //add new row to table
                	    var myRows  =   document.getElementById('available_properties').rows.length;
                        var myTable =   document.getElementById('available_properties').insertRow(myRows);
                        var myCellN =   myTable.insertCell(0);
                        var myCellV =   myTable.insertCell(1);
            
                        myCellN.innerHTML = data["inherit"]["name"]+':';
                        myCellN.className = 'name';
                        myCellN.id        = 'proptag_'+data["inherit"]["name"];
                        myCellV.innerHTML = data["inherit"]["value"]+' (inherited)';
                        myCellV.className = 'value';
                        myCellV.id        = 'propvalue_'+data["inherit"]["name"];
                        myTable.id        = 'proprow_'+data["inherit"]["name"];
                        
                        
                        Fat.fade_element('proprow_'+data["inherit"]["name"],10,1000,"#ffffcc");
        		    }
        			
        			
                    //hide the loader
    				hideLoad();
        		}
        });
    }
}


function addFile(filename,fileid,filesize,nodeid,pageid,filepath){
    //make sure there is no "no props" row
    deleteRow('nofiles');
    
	//add new row to table
	if(!document.getElementById('filerow_'+fileid)){
        var myRows  =   document.getElementById('available_files').rows.length;
        var myTable =   document.getElementById('available_files').insertRow(myRows);
        var myCellN =   myTable.insertCell(0);
    
        /*
        if(pageid){
            var filepath = '../files/pages/'+pageid+'/'+filename;    
        }else{
            var filepath = '../files/nodes/'+nodeid+'/'+filename;
        }
        */
        filepath = '../'+filepath+filename;
        
        myCellN.innerHTML = '<a href="'+filepath+'">'+filename+'</a> <span class="filesize">('+filesize+')</span> [<a href="javascript: deleteFile(\''+filename+'\',\''+fileid+'\',\''+nodeid+'\',\''+pageid+'\');" class="admin">x</a>]';
        myCellN.className = 'value';
        myTable.id        = 'filerow_'+fileid;
        
        Fat.fade_element('filerow_'+fileid,10,1000,"#ffffcc");
	}
	
    //empty fields
    //document.getElementById("fileloc").value  = '';
    
    //restore the view
    //unhide('addfilebtn',true); 
    unhide('addnew');
    hide('addfileform');
}


function deleteFile(filename,fileid,nodeid,pageid){
    if(confirm('Are You Sure You Want to Delete the File: '+filename+'?')){
        
        showLoad();
        deleteme('filerow_'+fileid);
        
        (new AjaxRequest).send({
        		url			: urlBase+"action=deleteFile",
        		data		: {
        			node    : nodeid,
        			page    : pageid,
        			file    : filename
        		},
        		
        		onSuccess	: function(data, info)
        		{
        			deleteRow('filerow_'+fileid);
        			
        			//check if that was the only file
        			var myRows = document.getElementById('available_files').rows.length;
        			if(myRows < 1){
        			    var myTable       =   document.getElementById('available_files').insertRow(myRows);
                        var myCellN       =   myTable.insertCell(0);
                        myCellN.innerHTML = '<div align="center"><i>No Files</i></div>';
                        myTable.id        = 'nofiles';
        			}
        			
                    //hide the loader
    				hideLoad();
        		}
        });
    }
}


function addDatablock(nodeid, pageid){
    
    //get the id of the selected option
    //
    var myOptions = document.getElementById('datablocks');
    var selectedO = myOptions.selectedIndex;
    
    //first, see if I want to make a new datablock?
    //NewWindow
    if(myOptions.options[selectedO].value == 'new'){
        NewWindow('/admin/sitestructure/?action=data&node='+nodeid+'&page='+pageid,'newdata',640,640,'no');
    }else{
        
        showLoad();
        (new AjaxRequest).send({
    		url			: urlBase+"action=addDatablock",
    		data		: {
    			node    : nodeid,
    			page    : pageid,
    			block   : myOptions.options[selectedO].value
    		},
    		
    		onSuccess	: function(data, info)
    		{
    			if(data["status"] == false){
    			    alert('There is already a datablock with the same tag "'+data["tag"]+'", titled "'+data["title"]+'"! Please choose another block, or create a new one.');
    			}else{
        		    //make sure there is no "no props" row
        		    deleteRow('nodata');
        		    
        			//add new row to table
        			if(!document.getElementById('datarow_'+data["tag"])){
                	    var myRows  =   document.getElementById('available_data').rows.length;
                        var myTable =   document.getElementById('available_data').insertRow(myRows);
                        var myCellN =   myTable.insertCell(0);
            
                        myCellN.innerHTML = '<a href="javascript: editData(\''+myOptions.options[selectedO].value+'\',\''+nodeid+'\',\''+pageid+'\');">'+myOptions.options[selectedO].label+'</a> [<a href="javascript: deleteData(\''+myOptions.options[selectedO].value+'\',\''+nodeid+'\',\''+pageid+'\',\''+data["tag"]+'\');" class="admin">x</a>]';
                        myCellN.id        = 'datatitle_'+data["tag"];
                        myTable.id        = 'datarow_'+data["tag"];
        			}else{
        			    document.getElementById('datatitle_'+data["tag"]).innerHTML = '<a href="javascript: editData(\''+myOptions.options[selectedO].value+'\',\''+nodeid+'\',\''+pageid+'\');">'+myOptions.options[selectedO].label+'</a> [<a href="javascript: deleteData(\''+myOptions.options[selectedO].value+'\',\''+nodeid+'\',\''+pageid+'\',\''+data["tag"]+'\');" class="admin">x</a>]';
        			}
        			
                    Fat.fade_element('datarow_'+data["tag"],10,1000,"#ffffcc");
                    
                    //restore the view
                    unhide('adddatabtn',true); 
                    hide('adddataform',true);
        			myOptions.options[selectedO] = null;
    			}
    			
                //hide the loader
    			hideLoad();
    		}
    	});
    }
}


function editData(id,nodeid,pageid){
    NewWindow('/admin/sitestructure/?action=data&node='+nodeid+'&block='+id+'&page='+pageid,'newdata',640,640,'no');
}


function deleteData(id,nodeid,pageid,tag){
    if(confirm('Are You Sure You Want to Delete the Datablock?')){
        
        showLoad();
        deleteme('datarow_'+tag);
        
        (new AjaxRequest).send({
        		url			: urlBase+"action=deleteDatablock",
        		data		: {
        			node    : nodeid,
        			page    : pageid,
        			id      : id
        		},
        		
        		onSuccess	: function(data, info)
        		{
        		    deleteRow('datarow_'+tag);
        		    
        		    //see if this datablock was an override of
        		    //an inheritance
        		    if(!data["inherit"]){
        		        
        			    //check if that was the only file
            			var myRows = document.getElementById('available_data').rows.length;
            			if(myRows < 1){
            			    var myTable       =   document.getElementById('available_data').insertRow(myRows);
                            var myCellN       =   myTable.insertCell(0);
                            myCellN.innerHTML = '<div align="center"><i>No Datablocks</i></div>';
                            myTable.id        = 'nodata';
            			}
            			
        		    }else{
        		        
        		        
        		        //add new row to table
                	    var myRows  =   document.getElementById('available_data').rows.length;
                        var myTable =   document.getElementById('available_data').insertRow(myRows);
                        var myCellN =   myTable.insertCell(0);
            
                        myCellN.innerHTML = data["inherit"]["title"]+' (inherited)';
                        myCellN.id        = 'datatitle_'+data["inherit"]["tag"];
                        myTable.id        = 'datarow_'+data["inherit"]["tag"];
                        
                        Fat.fade_element('datarow_'+data["inherit"]["tag"],10,1000,"#ffffcc");
        		    }
        			
        			
        			//add the deleted datablock to the dropdown
        			if(data["global"]){
            			var myOptions = document.getElementById('datablocks');
            			var totalOpts = myOptions.options.length;
            			myOptions.options[totalOpts] = new Option(data["title"],data["id"]);
            			myOptions.options[totalOpts].label = data["title"];
        			}
        			
                    //hide the loader
    				hideLoad();
        		}
        });
    }
}


function deleteImage(nodeid,pageid){
    if(confirm('Are You Sure You Want to Delete the Image?')){
        
        showLoad();
        deleteme('nodeimgdiv');
        
        (new AjaxRequest).send({
        		url			: urlBase+"action=deleteImage",
        		data		: {
        			node    : nodeid,
        			page    : pageid
        		},
        		
        		onSuccess	: function(data, info)
        		{
        			deleteRow('nodeimgdiv');
        			
        			unhide('upimg');
        			$('imgSet').value = 'f';
                    //hide the loader
    				hideLoad();
        		}
        });
    }
}

function deleteGalleryImage(pageid){
    if(confirm('Are You Sure You Want to Delete the Image?')){
        
        showLoad();
        deleteme('nodeimgdiv');
        
        (new AjaxRequest).send({
        		url			: urlBase+"action=deleteImage",
        		data		: {
        			image    : pageid
        		},
        		
        		onSuccess	: function(data, info)
        		{
        			deleteRow('nodeimgdiv');
        			$('imgSet').value = false;
        			
        			unhide('upimg');
        			
                    //hide the loader
    				hideLoad();
        		}
        });
    }
}


function hideTeaser(){
    hide('hide'); 
    unhide('unhide'); 
    hide('teaser');
}

function unhideTeaser(){
    unhide('hide'); 
    hide('unhide'); 
    unhide('teaser');
}


function cancelUpload(){
    hide('addfileform',true);
    $('addfile').show(); 
}

function showUpload(){
    $('addfile').hide(); 
    unhide('addfileform',true); 
}


function checkEstateType(elem) {
    if (elem.value == 'new') {
        $('new_estate_type').show();
        $('new_estate_type').focus();
    } else {
        $('new_estate_type').hide();
    }
}

function dropEstatePic(pid, isAGroundplan){
    if(confirm('Are You Sure You Want to Delete the Image?')){
        
        showLoad();
        deleteme('estatepicture_'+pid);
        
        (new AjaxRequest).send({
                url         : urlBase+"action=deleteEstateImage",
                data        : {
                    image        : pid,
                    isGroundplan : isAGroundplan
                },
                
                onSuccess   : function(data, info)
                {
                    $('estatepicture_'+pid).hide();
                    
                    //hide the loader
                    hideLoad();
                }
        });
    }
}

function reorderEstatePictures() {
    showLoad();
    
    (new AjaxRequest).send({
            url         : urlBase+"action=reorderEstateImages",
            data        : {
                order_pos   : Sortable.serialize("estatepictures")
            },
            
            onSuccess   : function(data, info)
            {
                //hide the loader
                hideLoad();
            }
    });
}

function cloneRow(tid,pos){

    if(!pos){
        pos = document.getElementById(tid).getElementsByTagName('tbody')[0].getElementsByTagName('tr').length - 1;
    }

    var tab   = document.getElementById(tid);
    var root  = tab.getElementsByTagName('tr')[pos].parentNode;     //the TBODY
    var clone = tab.getElementsByTagName('tr')[pos].cloneNode(true);//the clone of the first row     
    root.appendChild(clone);//appends the clone 
}